package com.leo.utils;

import android.content.Context;
import android.graphics.Rect;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.TouchDelegate;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;

/**
 * Created by leo on 16/4/26.
 *
 * 视图相关的处理类
 */
public class ViewUtils {
    /**
     *
     * function: 加载布局
     *
     * @param context
     * @param layoutId
     * @return
     * @author:Zhangguobao 2015-8-11 下午3:36:45
     */
    public static final View loadLayout(Context context, int layoutId) {
        return loadLayout(context, layoutId, null);
    }

    public static final View loadLayout(Context context, int layoutId, ViewGroup gp) {
        return loadLayout(context, layoutId, gp, gp != null);
    }

    public static final View loadLayout(Context context, int layoutId, ViewGroup gp, boolean attach) {
        return LayoutInflater.from(context).inflate(layoutId, gp, attach);
    }

    /**
     * 有内容就显示，没内容隐藏
     * 以content判断
     */
    public static void setTextToView(TextView tv, String content) {
        setTextToView(tv, content, content);
    }

    /**
     * 有内容就显示，没内容隐藏
     * 以condition判断
     */
    public static void setTextToView(TextView tv, String condition, String content) {
        if (tv == null) {
            return;
        }
        if (TextUtils.isEmpty(condition)) {
            tv.setVisibility(View.GONE);
        } else {
            tv.setVisibility(View.VISIBLE);
            tv.setText(content);
        }
    }

    /**
     * 点击效果
     *
     * @param view
     */
    public static void doClickAnim(View view) {
        AlphaAnimation anim = new AlphaAnimation(1f, 0.5f);
        anim.setDuration(200);
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        view.startAnimation(anim);
    }

    /**
     *      增加点击区域
     * @param view
     * @param top
     * @param bottom
     * @param left
     * @param right
     */
    public static void expandViewTouchDelegate(final View view, final int top,
                                               final int bottom, final int left, final int right) {
        ((View) view.getParent()).post(new Runnable() {
            @Override
            public void run() {
                Rect bounds = new Rect();
                view.setEnabled(true);
                view.getHitRect(bounds);

                bounds.top -= top;
                bounds.bottom += bottom;
                bounds.left -= left;
                bounds.right += right;

                TouchDelegate touchDelegate = new TouchDelegate(bounds, view);

                if (View.class.isInstance(view.getParent())) {
                    ((View) view.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });
    }

}
